package com.linkq.ipinyin.utils;

import cn.hutool.core.util.IdUtil;
import com.linkq.ipinyin.model.BcFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;

/**
 * ClassName: FileUtils
 * Description:
 * date: 2022/1/18 15:52
 *
 * @author wp
 */
@Component
public class FileUtils {

    public static String preFilePath;

    @Value("${file.upload-path}")
    public void setPreFilePath(String filePath) {
        preFilePath = filePath;
    }

    public static InputStream BaseToInputStream(String base64string){
        ByteArrayInputStream stream = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes1 = decoder.decodeBuffer(base64string);
            stream = new ByteArrayInputStream(bytes1);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return stream;
    }

    /**
     * 文件转byte[]
     * @param file
     * @return
     */
    public static byte[] fileToByte(File file){
        byte[] bytes = null;
        FileInputStream inputStream = null;
        try{
            inputStream = new FileInputStream(file);
            bytes = new byte[(int) file.length()];
            inputStream.read(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return bytes;
        }finally {
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
                return bytes;
            }
        }
        return bytes;
    }

    public static BcFile upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String fileType = file.getContentType();
        String filePath = preFilePath + fileName;
        String sourceName = IdUtil.simpleUUID() + fileName.substring(fileName.indexOf(".") - 1);
        BcFile bcFile = new BcFile();
        bcFile.setFileName(fileName);
        bcFile.setFileType(fileType);
        bcFile.setFilePath(filePath);
        bcFile.setSourceName(sourceName);
        File newFile = new File(preFilePath + sourceName);
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return bcFile;
    }
}
